package com.example.AiLangLearn.image_generation;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.AiLangLearn.R;
import com.iflytek.sparkchain.core.LLM;
import com.iflytek.sparkchain.core.LLMCallbacks;
import com.iflytek.sparkchain.core.LLMError;
import com.iflytek.sparkchain.core.LLMEvent;
import com.iflytek.sparkchain.core.LLMFactory;
import com.iflytek.sparkchain.core.LLMOutput;
import com.iflytek.sparkchain.core.LLMResult;

public class ImageGenerationActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "AEE_ImageGeneration";
    LLM llm;
    private ImageView imageView;
    private TextView tv_result,btn_imageGeneration_arun_start,btn_imageGeneration_stop;
    private EditText ed_input;
    private boolean isAuth = false;
    /*********
     * 图片生成结果监听回调
     * ***********/
    private LLMCallbacks mLLMCallbacksListener = new LLMCallbacks() {
        @Override
        public void onLLMResult(LLMResult result, Object o) {
            byte [] bytes = result.getImage();//获取图片生成结果二进制流，大模型一次性返回
            showImage(bytes);
            showInfo("图片生成结束");
        }

        @Override
        public void onLLMEvent(LLMEvent llmEvent, Object o) {

        }

        @Override
        public void onLLMError(LLMError error, Object o) {
            int errCode = error.getErrCode();
            String errMsg = error.getErrMsg();
            String errInfo = "出错了, 错误码:" + errCode + ",错误信息:" + errMsg;
            showInfo(errInfo);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_generation);
        Window window = this.getWindow(); window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        ed_input = findViewById(R.id.imageGeneration_input_text);
        imageView = findViewById(R.id.imageGeneration_output_iv);
        tv_result = findViewById(R.id.imageGeneration_Notification);
        btn_imageGeneration_arun_start = findViewById(R.id.imageGeneration_arun_start_btn);
        btn_imageGeneration_stop = findViewById(R.id.imageGeneration_stop_btn);
        btn_imageGeneration_arun_start.setOnClickListener(this);
        btn_imageGeneration_stop.setOnClickListener(this);
        setLLMConfig();
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.imageGeneration_arun_start_btn:
                if(ed_input.getText().toString().length() > 0) {
                    if (llm != null) {
                        clearImage();
                        showInfo("图片生成中, 请稍后......");
                        isAuth = true;
                        imageGeneration_arun_start();
                    }
                }else{
                    Toast.makeText(this, "文字描述不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.imageGeneration_stop_btn:
                if(llm != null && isAuth){
                    isAuth = false;
                    imageGeneration_stop();
                    showInfo("已取消图片生成");
                }
                break;
        }
    }
    /***************
     * 取消交互
     * ****************/
    private void imageGeneration_stop(){
        llm.stop();
    }
    /***************
     * 开始交互，异步
     * ****************/
    private void imageGeneration_arun_start(){
        String content = ed_input.getText().toString();
        Log.d("SparkChain","content: " + content);
        //异步请求
        llm.arun(content);
    }
    /***************
     * 开始交互，同步
     * ****************/
    private void imageGeneration_run_start(){
        String content = ed_input.getText().toString();
        Log.d("SparkChain","content: " + content);
        //同步请求
        LLMOutput syncOutput = llm.run(content);
        if(syncOutput.getErrCode() == 0) {
            byte [] bytes = syncOutput.getImage();
            if(bytes!=null)
                Log.d(TAG, "同步调用：" +  bytes.length);
            else {
                Log.d(TAG, "同步调用：获取结果失败");
                return;
            }
            showImage(bytes);
            showInfo("图片生成结束");
        }else {
            Log.d(TAG, "同步调用：" +  "errCode" + syncOutput.getErrCode() + " errMsg:" + syncOutput.getErrMsg());
        }
    }


    private void showImage(byte [] bytes){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);//把二进制图片流转换成图片
                imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp,bmp.getWidth(),bmp.getHeight(),false));//把图片设置到对应的控件
            }
        });
    }

    private void clearImage(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageView.setImageDrawable(null);
            }
        });
    }

    private void showInfo(String text){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_result.setText(text);
            }
        });
    }
    /***************
     * 配置文本交互LLM，注册结果监听回调
     * ******************/
    private void setLLMConfig(){
        llm = LLMFactory.imageGeneration(1024,1024);
        llm.registerLLMCallbacks(mLLMCallbacksListener);
    }
}
